<template>
	<view class="create-group" :style="{background: activeType==-1?'#f2f2f2':'#fff'}">
		<uni-nav-bar dark left-text="取消" :fixed="true" :title="titleText" background-color="#fff" color="#262E3F" @clickLeft="cancel()" />
		<view class="search-view">
			<view class="search-box">
				<uni-icons customPrefix="iconfont" type="icon-sousuo" size="32rpx"></uni-icons>
				<input class="input" type="text" :value="searchText" :focus="searchFocus" @input="searchInput" placeholder="搜索联系人" placeholder-style="color: #d7d7d7;" confirm-type="search" @confirm="search()">
			</view>
		</view>
		<view class="select-contack" :class="{'select-contack1': activeType==-1}" v-if="selectAllInfo.length>0">
			<view class="image-list">
				<view class="user-item" v-for="(item, i) in selectAllInfo" :key="i">
					<image :src="handleHead(item)" mode="aspectFill"></image>
					<text>{{item.name}}</text>
				</view>
				
			</view>
			<uni-icons type="right" @click="selectedContact"></uni-icons>
		</view>
		<view class="title" v-if="activeType==-1">
			选择联系人
		</view>
		<view class="" v-if="resultList.length>0">
			<view class="txl-org-item" v-for="(item, i) in resultList" :key="i" @click="radioChange(item)">
				 <uni-icons v-if="selectAllInfo.findIndex(info=>info.accountId == item.accountId)!=-1" type="checkbox-filled" color="#02A7F0" size="40rpx"></uni-icons>
                    <uni-icons v-else type="circle" size="40rpx"></uni-icons>
				<view class="logo-name">
					<image class="logo" :src="utils.headImage(item)" mode="aspectFill"></image>
					<text class="name">{{item.name}}</text>
				</view>
				<view class="no-wrap">
					<text class="type" v-if="0">校长</text>
					<uni-icons @click.stop="this.utils.userDetails(item.accountId, item.userType)" customPrefix="iconfont" type="icon-icon--" size="40rpx"></uni-icons>
				</view>
			</view>
		</view>
		<view class="no-result" v-else-if="searchText">
			<image src="/static/txl/ku.svg" mode="aspectFill"></image>
			<text>没有搜索到结果</text>
		</view>
		<view class="content" v-if="!searchText">
			<view class="contact-list" v-if="activeType==-1">
				<view class="item" v-for="(item, i) in list" :key="i">
					<view class="info" @click="selectGroup(item.type)">
						<view class="logo-name">
							<image class="logo" :src="`/static/txl/${item.icon}.png`" mode="aspectFill"></image>
							<text class="name">{{item.name}}</text>
						</view>
						<uni-icons type="forward" color="#aaa"></uni-icons>
					</view>
				</view>
			</view>
			<groups v-else-if="activeType==1"
				:chat-group="runChatGroup"
				:step-bar="stepBar"
				:type="2"
				@selectIds="selectIds"
				@selectGroup="selectGroup"></groups>
			<contact
				v-else-if="activeType==2"
				:star-contact="runChatGroup"
				:step-bar="stepBar"
				:type="2"
				@selectGroup="selectGroup"
			></contact>
			<view class="" v-if="activeType==3">
				<org-structure
					:mail-list="mailList"
					:step-bar="stepBar"
					:operation-type="publish||groupId?3:2"
					:role-type="publish"
					:isOnshow="isOnshow"
					@selectIds="selectIds"
					@selectGroup="selectGroup"></org-structure>
			</view>
		</view>
		<view class="create-btn">
			<view class="num">已选：{{stu_tea_number}}人{{departmentIds.length}}部门</view>
			<text class="btn" @click="createChatGroup()">{{publish||groupId?'确定':'创建'}}</text>
		</view>
	</view>
</template>
<script>
import orgStructure from './components/org-structure.vue'
import groups from './components/groups.vue'
import contact from './components/contact.vue'
export default {
	components: {
		orgStructure,
		groups,
		contact
	},
	data() {
		return{
			titleText: '', // 标题内容
			searchText: '',
			searchFocus: false,
			resultList: [],
			activeId: -1,
			stepBar: [],
			list: [{name: '我管理的群组', icon: 'wdqz', type: 1}, {name: '组织架构', icon: 'xblx', type: 3}], // , {name: '外部联系人', icon: 'wblxr', type: 2}
			// 组织结构
			mailList: {},
			showMailList: [],
			adminList: [],
			activeType: -1,
			// 已选择创群的组织
			stu_tea_number: 0,
			allAdminStudent: [],
			studentIds: [],
			adminIds: [],
			departmentIds: [],
			runChatGroup: [],

			selectAllInfo: [],
			groupId: '', // 添加群成员,
			isOnshow: 1,
			publish: '', // 1.从发布活动页面过来的
		} 
	},
	// #ifdef APP-PLUS
	onBackPress() {
		if(this.activeType!=-1){
			return true;
		}
		
		
	},
	// #endif
	onShow(){
		this.isOnshow ++
		this.selectAllInfo = uni.getStorageSync('xdSelectAllInfo') || []
	},
	onLoad(options) {
		this.titleText = options.title || '创建群组'
		this.groupId = options.groupId || '';
		this.publish = options.publish || '';
		this.getfindMailList()
		this.getmyChatGroup()
	},
	methods:{
		
		handleHead(item){
			return item.qun?`/static/txl/qlx${item.type>3?'3':item.type}.png`:item.userType?this.utils.headImage(item):'/static/txl/zzjg-icon.png'
		},
		cancel(){
			this.activeType = -1
			uni.removeStorageSync('xdSelectAllInfo')
			uni.navigateBack({
				delta: 1
			})
		},
		selectedContact(){
			uni.setStorageSync('xdSelectAllInfo', this.selectAllInfo)
			uni.navigateTo({
				url: '/pages/addressBook/selected-contacts'
			})
		},
		// 组织架构数据
		getfindMailList(){
			this.api.get('mailList/findMailList').then(res=>{
				if(res.data.state != 'ok') return;
				let data = res.data.node;
				this.mailList = data
				this.allAdminStudent = data.admins;
				this.dataList = data.children || [];
				let that = this;
				function fun(list){
					for(let i=0; i<list.length; i++){
						let datas = list[i]
						if(datas.type==3){
							that.allAdminStudent = that.allAdminStudent.concat(datas.admins, datas.students);
						}else if(datas.type>0){
							let arr = datas.children;
							fun(arr)
							that.allAdminStudent = that.allAdminStudent.concat(datas.admins);
							
						}
					}
					
				}
				fun(this.dataList)
			})
		},
		// 我管理的群数据
		getmyChatGroup(index) {
			this.api.get('mailList/myChatGroup').then(res=>{
				if(res.data.state!='ok') return;
				let data = res.data;
				// this.chatGroupUsers = data.chatGroupUsers;
				this.runChatGroup = data.runChatGroup;
			})
		},
		focus(){
			this.searchFocus = true
		},
		searchInput(e){
			this.searchText = e.detail.value;
			
			this.search()
		},
		search(){
			let resultList = [], that = this;
			if(!this.searchText) {
				this.resultList = []
				return
			}
			for(let i=0;i<this.allAdminStudent.length; i++){
				let info = this.allAdminStudent[i]||{}
				let inx = resultList.findIndex(item=>item.id==info.id&&item.type==info.type)
				if(info.name&&info.name.indexOf(this.searchText)!=-1 && inx==-1){

					resultList.push(info)
				}
			}
			this.resultList = resultList;
			
		},
		// 进度条
		setStepBar(data){
			this.stepBar.push(data);
		},
		setActiveId(id){
			this.activeId = id
		},
		selectGroup(type){
			this.activeType = type;
			this.stepBar = []
			if(type == -1) return;
			this.stepBar.push({id: -1, name: '联系人'})
		},
		// 创建群操作
		selectIds(data, info){
			this.studentIds = data.student || []
			this.adminIds = data.admin || []
			this.departmentIds = data.department ||[]
			this.stu_tea_number = this.studentIds.length+this.adminIds.length

			let type = info.type, index = this.selectAllInfo.findIndex(item=>item.type == type)
			if(index==-1){
				this.selectAllInfo.push(info);
			}else{
				this.selectAllInfo.splice(index, 1)
			}
			
		},
		createChatGroup(){
			// 选择评审老师

			if(this.publish){
				// 审核人列表
				uni.setStorageSync('xdReviewerList', this.adminIds)
				this.cancel()
				return
			}
			// 添加群成员
			if(this.groupId){
				this.api.post('chatGroupManage/addMembers', {
					chatGroupId: this.groupId,
					accountIds: JSON.stringify(this.studentIds.concat(this.adminIds))
				}).then(res=>{
					this.cancel()
				})
				return
			}
			// 创建群
			let studentIds = [], adminIds = [], chatGroupList = [], departmentIds = []

			for(let i=0;i<this.selectAllInfo.length;i++){
				let info = this.selectAllInfo[i]
				if(info.userType==2){
					studentIds.push(info.accountId)
				}else if(info.userType==1){
					adminIds.push(info.accountId)
				}else if(info.qun==1){
					chatGroupList.push(info.id)
				}else if(!info.userType){
					departmentIds.push({id: info.id, stratum: info.type})
				}
			}
			
			this.api.post('chatGroupManage/createChatGroup', {
				accountIds: JSON.stringify(studentIds.concat(adminIds)),
				chatGroupList: JSON.stringify(chatGroupList),
				departmentList: JSON.stringify(departmentIds)
			}).then(res=>{
				if(res.data.state != 'ok')return
				uni.redirectTo({
					url: `/pages/chatSystem/group-msg?examId=${res.data.groupId}&create=1`
				})
			})
		},
		radioChange(info){
			let type = info.type,
			id = info.id,
			userType = info.userType;
            let index = -1;
            if(userType == 2){
                index = this.studentIds.indexOf(id);
                if(index!=-1){
                    this.studentIds.splice(index, 1)
                }else{
                    this.studentIds.push(id)
                }
                
            }else if(userType == 1){
                index = this.adminIds.indexOf(id);
                if(index!=-1){
                    this.adminIds.splice(index, 1)
                }else{
                    this.adminIds.push(id)
                }
            }
            let obj = {
                student: this.studentIds,
                admin: this.adminIds
            }
            let item = {accountId: info.accountId, id: info.id, type: `${info.type||0}:${info.id}`,avatarUrl: info.avatarUrl||'', name: info.name, userType: info.userType, sex: info.sex}
			this.selectIds(obj, item)
        },
	}
}
</script>
<style lang="less" scoped>
	.create-group{
		/* #ifdef H5 */
		min-height: calc(100vh - 44px);
		/* #endif */
		/* #ifdef APP-PLUS */
		min-height: 100vh;
		/* #endif */
		overflow: hidden;
	}
	
	.search-view{
		padding: 40rpx 28rpx;
		background-color: #fff;
	}
	.search-box{
		
		padding: 0 20rpx;
		height: 34px;
		display: flex;
		align-items: center;
		border: 2rpx solid #d7d7d7;
		border-radius: 10rpx;
		font-size: 26rpx;
		.input{
			width: 84%;
			margin: 0 24rpx;
			font-size: 26rpx;
		}
	}
	.select-contack{
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
		padding: 0 32rpx 20rpx;
		border-bottom: 10rpx solid #f2f2f2;
		margin-bottom: 30rpx;
		
	}
	.select-contack1{
		border: none;
		margin-bottom: 0;
	}
	.image-list{
		width: 92%;
		white-space: nowrap;
		overflow-x: scroll;
		display: flex;
		.user-item{
			margin-right: 40rpx;
			width: 88rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}
		text{
			margin-top: 16rpx;
			white-space: nowrap;
			text-overflow: ellipsis;
			overflow: hidden;
			font-weight: bold;
			line-height: 32rpx;
		}
		image{
			width: 88rpx;
			height: 88rpx;
			border-radius: 44rpx;
		}
	}
	.title{
		padding-left: 32rpx;
		padding-top: 16rpx;
		height: 60rpx;
		box-sizing: border-box;
	}
	.content{
		// padding-top: 30rpx;
		background-color: #fff;
		margin-bottom: 100rpx;
	}
	.contact-list{
		background-color: #fff;
	}
	.item {
		padding: 8rpx 20rpx 8rpx 16rpx;
	}
	.info{
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 32rpx 0 16rpx;
		&:active{
			background-color: #f2f2f2;
			border-radius: 10rpx;
		}
	}
	.logo{
		width: 32rpx;
		height: 32rpx;
		margin-right: 26rpx;
	}
	.name{
		vertical-align: 6rpx;
		font-size: 28rpx;
	}
	.create-btn{
		position: fixed;
		left: var(--window-left);
		right: var(--window-right);
		bottom: 0;
		padding: 0 32rpx;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.num{
			color: #55acee;
		}
		.btn{
			width: 124rpx;
			height: 60rpx;
			line-height: 60rpx;
			background-color: #169bd5;
			border-radius: 10rpx;
			text-align: center;
			color: #fff;
			font-size: 26rpx;
		}
	}
	.no-result{
		height: calc(100vh - 400rpx);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		image{
			width: 100rpx;
			height: 100rpx;
			margin-bottom: 40rpx;
		}
	}
</style>